#include "UDPInterface.h"


#include <unistd.h>
#include <stdarg.h>




#include "SysLog.h"


// If the size of the buffer is too large, will take more than 1 time to send by UDP
int SendDataByUDP(int sockfd, const void *buf, size_t len, int flags, const struct sockaddr *dest_addr, socklen_t addrlen)
{
    NETWORK_COMM_STU sendCommStu;
    char *p = (char *)buf;
    char sendBuf[1024];
    
    int nTime = (len / 1024);
    int successRet = 0;
    int ret = 0;

    // not the last time
    for(; nTime > 0; nTime--)
    {
        // printf("************* nTime = [%d] **************\n", nTime);
        memset(&sendCommStu, 0, sizeof(sendCommStu));
        memcpy(sendCommStu.cStrDataBuff, p, sizeof(sendCommStu.cStrDataBuff));
        sendCommStu.nSize = sizeof(sendCommStu.cStrDataBuff);
        sendCommStu.bLastFlag = false;

        ret = sendto(sockfd, (char *)&sendCommStu, sizeof(sendCommStu), flags, dest_addr, addrlen);
        successRet += ret;
        p +=ret;

        usleep(5000);
    }

    // last time
    memset(&sendCommStu, 0, sizeof(sendCommStu));
    memcpy(sendCommStu.cStrDataBuff, p, len - successRet);
    sendCommStu.nSize = len - successRet;
    sendCommStu.bLastFlag = true;

    // maybe the size is a bug
    ret = sendto(sockfd, (char *)&sendCommStu, sizeof(sendCommStu), flags, dest_addr, addrlen);
    successRet += ret;


    return successRet;
    
}

// Recv Data by UDP, can handle the many times situation.
int RecvDataByUDP(int sockfd, std::string &strRecvBuf, int flags, struct sockaddr *src_addr, socklen_t *addrlen)
{
    int nSuccessRet = 0;
    std::string strTmpRecvBuf;
    
    NETWORK_COMM_STU recvCommStu;
    memset(&recvCommStu, 0, sizeof(recvCommStu));

    // When there is a large amount of data, will recv many time.
    // so need to flag the last time to over the recv process
    while(true)
    {
        char recvBuf[MAX_COMM_SIZE];
        int ret = recvfrom(sockfd, recvBuf, MAX_COMM_SIZE, flags, src_addr, addrlen);

        memset(&recvCommStu, 0, sizeof(recvCommStu));
        memcpy(&recvCommStu, recvBuf, sizeof(recvCommStu));

        // append each time's data
        strTmpRecvBuf += recvCommStu.cStrDataBuff;
        nSuccessRet += ret;

        // last frame in this communication?
        if (recvCommStu.bLastFlag == true)
        {
            break;
        }
    }

    strRecvBuf = strTmpRecvBuf;

    return nSuccessRet;
} 